package dmxGroupControl.listeners;

import dmxGroupControl.StatusCode;
import oscP5.OscMessage;
import oscP5.OscP5;

import org.jdom2.Element;

import dmxGroupControl.Group;
import dmxGroupControl.Universe;

public class OSCListener extends Listener
{
	OscP5 osc;
	int listenPort;

	public OSCListener(String id, int listenPort)
	{
		super(id);
		osc = new OscP5(this, listenPort);
		this.listenPort = listenPort;
        UpdateStatus(StatusCode.NOTHING_RECEIVED);
	}

	public void close()
	{
		osc.stop();
	}
	
	@Override
	public void ParseMappings(Universe universe, int fixtureStartIndex, Element xmlEntry)
    {
	    super.ParseMappings(fixtureStartIndex);
        for (Element element : xmlEntry.getChildren("mapping"))
        {
            String address = element.getAttributeValue("address");
            String channel = element.getAttributeValue("channel");
            Mapping mapping = new OscMessageMapping(universe, address, channel);
            mappings.Add(mapping);
        }
    }

	void oscEvent(OscMessage message)
	{
		if (!GetActive())
		{
			return;
		}
        if(mappings.HasMatchFor(message))
		{
            if(!AlreadyGreen())
            {
                UpdateStatus(StatusCode.DATA_RECEIVED);
            }
            Mapping mapping = mappings.GetMatchFor(message);
			int groupNumber = mapping.GetGroup(message, fixtureStartIndex);
			String attribute = mapping.GetAttribute();
			float value = mapping.GetValue(message);
			if (groupNumber < mapping.GetUniverse().GetGroups().size())
			{
				Group group = mapping.GetUniverse().GetGroups().get(groupNumber);
				group.Set(attribute, value);
			}
		}
	}
	
	public int GetPort()
	{
		return listenPort;
	}

	@Override
	public String GetType()
	{
		return "osc";
	}

	@Override
	public String GetAddress()
	{
		return listenPort + "";
	}
	
	@Override
	public String toString()
	{
		return "OSC Listener -" + listenPort;
	}
}
